package unrn.isiii.bean;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import unrn.isiii.dao.ClienteDao;
import unrn.isiii.dao.TaskDao;
import unrn.isiii.model.Cliente;
import unrn.isiii.model.Task;

@Component("clienteController")
public class ClienteController {

	private static final Logger logger = LoggerFactory
			.getLogger(ClienteController.class);

	private Cliente cliente = new Cliente();
	private List<Cliente> clientes;

	@Autowired
	private ClienteDao clienteDao;

	public String getMessage() {
		logger.debug("Returning message from task home bean");
		return "Hello from Spring";
	}

	public Cliente getCliente() {
		return cliente;
	}

	public ClienteDao getClienteDao() {
		return clienteDao;
	}

	public void setClientekDao(ClienteDao clienteDao) {
		this.clienteDao = clienteDao;
	}

	public void setCliente(Cliente cliente) {
		this.cliente = cliente;
	}

	public void setClientes(List<Cliente> clientes) {
		this.clientes = clientes;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void saveCliente() {
		if (cliente.getDni() == null)
			clienteDao.create(cliente);
		else
			clienteDao.update(cliente);
		cliente = new Cliente();
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"realizada con exito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void eliminar(Long id) {
		clienteDao.delete(id);
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Alta",
				"realizada con exito.");
		if (FacesContext.getCurrentInstance() != null)
			FacesContext.getCurrentInstance().addMessage(null, msg);
		invalidateTasks();
	}

	private void invalidateTasks() {
		clientes = null;
	}

	public List<Cliente> getClientes() {
		if (clientes == null) {
			clientes = clienteDao.findAll();
		}
		return clientes;
	}

	public void seleccionarCliente(Cliente cliente) {
		setCliente(cliente);
	}
}
